package com.kandinfo.survey.common.service.impl;

import java.util.Date;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kandinfo.base.common.service.AbstractService;
import com.kandinfo.base.security.SecurityContext;
import com.kandinfo.base.security.domain.User;
import com.kandinfo.survey.common.constants.StatusConstant;
import com.kandinfo.survey.common.domain.UserQuestionnaireRela;
import com.kandinfo.survey.common.repository.UserQuestionnaireRelaRepository;
import com.kandinfo.survey.common.service.UserQuestionnaireRelaService;

@Service
public class UserQuestionnaireRelaServiceImpl
        extends AbstractService<UserQuestionnaireRela, Long, UserQuestionnaireRelaRepository>
        implements UserQuestionnaireRelaService {

    private static final Logger logger = LoggerFactory.getLogger(UserQuestionnaireRelaServiceImpl.class);

    @Resource
    public void setUserQuestionnaireRelaRepository(UserQuestionnaireRelaRepository userQuestionnaireRelaRepository) {
        super.setRepository(userQuestionnaireRelaRepository);
    }

    @Override
    @Transactional
    public void saveRela(Long questionnaireId) {
        // get user
        User curUser = SecurityContext.getInstance().getCurrentUser();

        UserQuestionnaireRela relaDomain = new UserQuestionnaireRela();
        relaDomain.setCreateBy(curUser.getId());
        relaDomain.setCreateTs(new Date());
        relaDomain.setQuestionnaireId(questionnaireId);
        relaDomain.setUserId(curUser.getId());
        relaDomain.setStatus(StatusConstant.NORMALLY_USE);

        repository.save(relaDomain);
    }

    @Override
    @Transactional
    public Boolean deleteRela(Long questionnaireId) {
        // get user
        User curUser = SecurityContext.getInstance().getCurrentUser();

        try {
            UserQuestionnaireRela domain = repository.findOneQuestionnaire(curUser.getId(), questionnaireId);
            if (null == domain) {
                return Boolean.FALSE;
            }
            domain.setStatus(StatusConstant.TOMBSTONED);
            domain.setUpdateBy(curUser.getId());
            domain.setUpdateTs(new Date());

            repository.saveAndFlush(domain);
            return Boolean.TRUE;
        } catch (Exception e) {
            logger.error(" UserQuestionnaireRela tomstoned fail, questionnaireId : {}" + questionnaireId
                    + ", userId : {}" + curUser.getId(), e.toString());
            return Boolean.FALSE;
        }
    }

}
